# Makefile - Generic handcrafted Makefile to build
#            a single binary file from a set of objects


# Some variables we use in our rules

CC = gcc		# The compiler
CPP_FLAGS =             # Preprocessor flags
C_FLAGS   = `pkg-config gtk+-2.0 --cflags` \
            `pkg-config libglade-2.0 --cflags` \
             -Wall -g # Compiler flags
LD_FLAGS  = `pkg-config gtk+-2.0 --libs` \
            `pkg-config libglade-2.0 --libs` # Linker flags
PACKAGE   = engcur

# This is our main targed: the binary (executable) file

all : $(PACKAGE)

# The variable $(objects) is a list with all objects we need

objects = main.o engcur.o support.o debug_funcs.o interfaces.o callbacks.o


# Implicit rule to make object files from source files
# This line tells that every file somename.o depends on
# a file somename.c, so all the obhect-source dependencies
# are handled by a single rule.
#
# Notice we are using our variables plus some special
# automatic variables such as $< (see info make)

%.o : %.c
	$(CC) $(CPP_FLAGS) $(C_FLAGS) $(CPPFLAGS) $(CFLAGS) -c $<  

# Object files usually depend also on header files.  This is
# a clever trick to automatically generate all the 
# header-object dependences. 

# We first create a variable with a list of makefiles, one for 
# each object we have.  We do it by means of the substitution
# function of make. The variable $(makefile) contains the
# list main.d foo.d bar.d (see info make) 

makefiles = $(objects:.o=.d)

# This is the magic. See how it works. When gcc is issued
# with the -MM flag, it outputs a line of the form: 
# file.o : header1.h header2.h ... where file.o is the
# source specified in the command line and header*.h are
# the header files included in it (only those include
# by the directive #include "header.h"). Notice that
# the output is syntatically valid makefile rule that
# tells which headers the object depends on.  What we
# do is to save each line of this type in a file.d, one
# per source, and then include them all in this makefile.
#
# This is almos what we need. There is one thing left:
# to tell that the object depends also on the makefile
# itself, that is, to say that file.o dependes also on
# file.d.  We do it by filtering the output of gcc -MM file.c
# so that it becomes file.o: file.d header1.h header2.h...
# We pipe the output of gcc into the sed utilitary, which
# uses a regular expression to do the job. Tricky, but
# once you understand it is clear cristal.

%.d: %.c
	set -e; $(CC) -MM $(CPPFLAGS) $< \
	| sed 's/\($*\)\.o[ :]*/\1.o $@ : /g' > $@; \
	[ -s $@ ] || rm -f $@

include $(makefiles)

# This is where we tell that our main binary (executable)
# file depends on all the objects.

$(PACKAGE) : $(objects)
	$(CC) $(LD_FLAGS) $(LDFLAGS) $(objects) -o $(PACKAGE)

# Finally, a rule to clean up the mess

clean:
	rm -f *.o \#* *~  *.d
	rm -f $(PACKAGE)
